<?php

namespace App\Trip\Wechat\Account;

use App\Models\User\User;
use Exception;

class WechatMIniAppLoginByMobile extends WechatMiniAppLogin
{
    /**
     * @throws Exception
     */
    public function login(): WechatLoginResp
    {

        $userData    = $this->decryptData();
        $mobile      = $userData['purePhoneNumber'] ?? '';
        $addUserData = [
            'openid'      => $userData['openid'],
            'unionid'     => $userData['unionid'],
            'avatar'      => $userData['avatarUrl'] ?? '',
            'nickname'    => $userData['nickName'] ?? '',
            'phone'       => $mobile,
            'appid'       => $this->miniapp->getAppId(),
            'client_type' => User::CLIENT_TYPE_WECHAT_MINIAPP,
        ];
        $user        = $this->userRepo->getUserByUnionIdOpenIdType($userData['unionid'], $userData['openid'], User::CLIENT_TYPE_WECHAT_MINIAPP);
        // 用户不存在如果电话号码不存在
        if (!$user || !$user?->getPhone()) {
            $user = $this->userRepo->addUser($addUserData);
        }
        // appUser
        $appUser = $this->userRepo->getMiniAppUserByOpenId($user, $userData['openid']);
        if ($appUser && !$appUser->getAppId()) {
            $this->appUserRepo->updateData($appUser, [
                'appid' => $this->miniapp->getAppId(),
            ]);
        } else {
            $this->userRepo->addMiniUser($user, $addUserData);
        }
        return new WechatLoginResp($user);
    }
}